package com.laikan.reader.bookfriend.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.Order;
import com.laikan.reader.core.utils.MD5Util;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.utils.VSofoPay;
import com.socks.library.KLog;
import com.vsofo.vsofopay.IPayResultCallback;
import com.vsofo.vsofopay.SDKAPI;

import java.lang.reflect.Type;
import java.util.HashMap;

public class VPayMoney extends BasicActivity implements OnClickListener {

    private TextView text1, text2, text3, text4, ten_text, twenty_text, thirty_text, fifty_text;
    private String money;
    private RelativeLayout ten, twenty, thirty, fifty;
    private ImageView back_tv;
    private RelativeLayout back_layout;
    Drawable drawable_back_tv;
    private boolean payAction;
    private String wzm;
    // SDK回调函数
    private IPayResultCallback payResultCallback = new IPayResultCallback() {
        @Override
        public void onPayResult(int resultCode, String description, String orderNumber) {
            onResult(resultCode, description, orderNumber);
        }
    };

    @Override
    protected void assignViews() {
        setContentView(R.layout.vpaymoney);
        text1 = (TextView)findViewById(R.id.text1);
        text2 = (TextView)findViewById(R.id.text2);
        text3 = (TextView)findViewById(R.id.text3);
        text4 = (TextView)findViewById(R.id.text4);
        text1.setRotation(40.0f);
        text2.setRotation(40.0f);
        text3.setRotation(40.0f);
        text4.setRotation(40.0f);

        ten_text = (TextView)findViewById(R.id.ten_text);
        twenty_text = (TextView)findViewById(R.id.twenty_text);
        thirty_text = (TextView)findViewById(R.id.thirty_text);
        fifty_text = (TextView)findViewById(R.id.fifty_text);

        ten = (RelativeLayout)findViewById(R.id.ten);
        twenty = (RelativeLayout)findViewById(R.id.twenty);
        thirty = (RelativeLayout)findViewById(R.id.thirty);
        fifty = (RelativeLayout)findViewById(R.id.fifty);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
    }

    @Override
    protected void initData() {
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
       /* payAction = getIntent().getBooleanExtra("payAction", true);
        if (payAction) {
            text1.setVisibility(View.VISIBLE);
            text2.setVisibility(View.VISIBLE);
            text3.setVisibility(View.VISIBLE);
            text4.setVisibility(View.VISIBLE);
            ten_text.setVisibility(View.VISIBLE);
            twenty_text.setVisibility(View.VISIBLE);
            thirty_text.setVisibility(View.VISIBLE);
            fifty_text.setVisibility(View.VISIBLE);
        }else {
            ten_text.setVisibility(View.GONE);
            twenty_text.setVisibility(View.GONE);
            thirty_text.setVisibility(View.GONE);
            fifty_text.setVisibility(View.GONE);
            text1.setVisibility(View.GONE);
            text2.setVisibility(View.GONE);
            text3.setVisibility(View.GONE);
            text4.setVisibility(View.GONE);
            ten.setBackgroundColor(Color.WHITE);
            twenty.setBackgroundColor(Color.WHITE);
            thirty.setBackgroundColor(Color.WHITE);
            fifty.setBackgroundColor(Color.WHITE);
        }*/
    }

    @Override
    protected void setListener() {

        ten.setOnClickListener(this);
        twenty.setOnClickListener(this);
        thirty.setOnClickListener(this);
        fifty.setOnClickListener(this);
        back_layout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.ten:
                money = "10";
                wzm = "500K币";
                getOrder();
                break;
            case R.id.twenty:
                money = "20";
                wzm = "1000K币";
                getOrder();
                break;
            case R.id.thirty:
                money = "30";
                wzm = "1500K币";
                getOrder();
                break;
            case R.id.fifty:
                money = "50";
                wzm = "2500K币";
                getOrder();
                break;
            case R.id.back_layout:
                finish();
                break;
        }
    }

    /**
     * @param mz 面值
     * @param uid 当前用户id
     * @param oid 订单号
     * @param spid 商户id
     */
    public void getVPay(String mz, String uid, String oid, String spid) {

        String md5 = MD5Util.exChange(MD5Util.stringToMD5(mz + uid + oid + spid));

        String spurl = VSofoPay.spurl + "?mz=" + mz + "&md5=" + md5 + "&uid=" + uid + "&oid=" + oid + "&spid=" + spid;
        SDKAPI.startPay(VPayMoney.this, spurl, wzm, payResultCallback);

    }

    public void onResult(int resultCode, String description, String orderNumber) {
        // 状态码
        // 100 提示内容：支付请求已提交，请返回账户查询。
        // 101 失败提示内容：根据SDK返回文本提示。
        // 102手动操作提示内容：请到收件箱接收短信，并根据短信回复确认内容完成支付。
        // 109提示内容：用户退出支付。（未支付就退出）
        //		KLog.v("onResult", "状态码：" + resultCode);
        //		KLog.v("onResult", "数据说明：" + description);
        //		KLog.v("onResult", "订单号：" + orderNumber);

        Toast.makeText(this, description, Toast.LENGTH_SHORT).show();
        if (100 == resultCode) {
            // 处理该订单的业务逻辑。
        }else if (101 == resultCode) {
            // 处理该订单的业务逻辑。
        }else if (102 == resultCode) {
            // 处理该订单的业务逻辑。
        }else if (109 == resultCode) {
            // 处理该订单的业务逻辑。
        }
        if (description.contains("yhxfsucc")) {
            if (SPUtil.getBoolean("signedAction", false)) {
                LocalBroadcastManager.getInstance(mContext).sendBroadcast(new Intent("action_signed"));
            }
        }
    }

    /**
     * 获取投票数据
     */
    public void getOrder() {
        String curr = System.currentTimeMillis() + "";
        final String mz = money;
        final String uid = SPUtil.getString("token", "");
        final String oid = curr;
        final String spid = VSofoPay.spid;
        String md5 = MD5Util.exChange(MD5Util.stringToMD5(mz + uid + oid + spid));
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("mz", mz);
        map.put("uid", uid);
        map.put("oid", oid);
        map.put("spid", spid);
        map.put("md5", md5);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                BaseDataBean<Order> orderResult;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<Order>>() {
                }.getType();
                try {
                    orderResult = gson.fromJson(httpResponse.responseContent, type);
                    if (null == orderResult || null == orderResult.getData() || !Constants.RESULT_OK.equals(orderResult.getResult())) {
                        ToastMgr.showShortToast(orderResult.getError_msg());
                    }else {

                        getVPay(mz, uid, orderResult.getData().getOrderId(), spid);
                    }

                }catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    KLog.e("1684 数据解析失败");
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_data_load_failed);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_vfubao_create_order);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_vfubao_create_order, map, null, null, requestListener);
    }

}
